import net.sourceforge.pinyin4j.PinyinHelper
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType

object PinyinUtils {
    /**
     * 将中文转化为拼音
     * 接收中文名
     * 返回完整的拼音
     * pengxiaodong
     * PengXiaoDong
     * PENGXIAODONG
     */
    fun toPinyin(name:String, type: PinyinType):String{
        val format = HanyuPinyinOutputFormat().also {
            it.caseType = if (type == PinyinType.ALL_UPPERCASE)
                HanyuPinyinCaseType.UPPERCASE
            else
                HanyuPinyinCaseType.LOWERCASE
            it.toneType = HanyuPinyinToneType.WITHOUT_TONE
        }

        //遍历name中的每一个中文汉字
        val wholeName = StringBuilder()
        for (word in name) {
            //将这个中文转化为拼音
            val pinyin = PinyinHelper.toHanyuPinyinStringArray(word,format).first()
            //彭  孝  东
            //PENG
            //peng   xiaodong
            //Peng
            if (type == PinyinType.WORD_FIRST_UPPERCASE) {
                //val newPinyin = pinyin[0].uppercase() + pinyin.drop(1)
                //将首字母转化为大写
                pinyin.mapIndexed { index, c ->
                    if (index == 0) c.uppercase() else c
                }.joinToString(separator = "").also {
                    wholeName.append(it)
                }
            }else{
                wholeName.append(pinyin)
            }
        }
        return wholeName.toString()
    }
}